#include "udp_serve.hpp"
#include <memory>
#include <string>
#include <iostream>
#include <stdio.h>

extern Log lg;
const size_t res_size = 4096;

void usage(const char* cmd)
{
    std::cout << "usager: " << cmd << "port[1024+]\n";
}

std::string handler(const std::string& s)
{
    return "serve echo# " + s;
}

// 对于使用这些端口，使用命令行的方式运行
std::string execute_cmd(const std::string& cmd)
{
    FILE* res = popen(cmd.c_str(), "r");
    if(nullptr == res)
    {
        perror("open");
        return "error";
    }
    std::string result;
    char buffer[res_size]= {0};
    while(fgets(buffer, sizeof buffer, res))
        result += buffer;
    int n = pclose(res);
    if(n < 0)
    {
        perror("pclose");
        return "error";
    }
    return result;
}


int main(int argc, char* args[])
{
    if(argc != 2)
    {
        usage(args[0]);
        return 0;
    }
    std::unique_ptr<udp_serve> pu(new udp_serve(atoi(args[1])));
    pu->init();
    pu->run(execute_cmd);
    return 0;
}